package com.training.web.service;

import com.training.bean.CourseStage;
import com.training.bean.StageAuthorization;
import com.training.bean.User;
import com.training.api.repository.CourseStageRepository;
import com.training.web.repository.WebAuthorizationRepository;
import com.training.web.repository.WebUserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class WebAuthorizationService {

    @Autowired
    private WebAuthorizationRepository authorizationRepository;
    
    @Autowired
    private WebUserRepository userRepository;
    
    @Autowired
    private CourseStageRepository stageRepository;
    public List<StageAuthorization> getAllAuthorizations() {
        List<StageAuthorization> authorizations = authorizationRepository.findAll();
        // 为每个授权信息补充用户昵称和阶段标题
        return authorizations.stream().map(auth -> {
            // 获取用户信息
            User user = userRepository.findById(auth.getUserId()).orElse(null);
            if (user != null) {
                auth.setUserNickname(user.getNickname());
            }
            
            // 获取阶段信息
            CourseStage stage = stageRepository.findById(auth.getStageId()).orElse(null);
            if (stage != null) {
                auth.setStageTitle(stage.getTitle());
            }
            
            return auth;
        }).collect(Collectors.toList());
    }

    public StageAuthorization addAuthorization(StageAuthorization authorization) {
        // 设置创建和更新时间
        Date now = new Date();
        authorization.setCreateTime(now);
        authorization.setUpdateTime(now);
        
        // 保存并返回保存后的对象
        return authorizationRepository.save(authorization);
    }

    public StageAuthorization updateAuthorization(StageAuthorization authorization) {
        // 获取数据库中已存在的授权信息
        StageAuthorization existingAuthorization = authorizationRepository.findById(authorization.getId()).orElse(null);
        
        // 如果存在，则保留原有的创建时间
        if (existingAuthorization != null) {
            authorization.setCreateTime(existingAuthorization.getCreateTime());
        }
        
        // 设置更新时间
        authorization.setUpdateTime(new Date());
        
        // 保存并返回保存后的对象
        return authorizationRepository.save(authorization);
    }

    public void deleteAuthorization(int id) {
        authorizationRepository.deleteById(id);
    }
}